package com.neusoft.hifly.core.token.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.neusoft.hifly.core.pojo.ApiResponse;
import com.neusoft.hifly.core.redis.RedisCache;
import com.neusoft.hifly.core.token.JwtUtil;
import com.neusoft.hifly.core.token.TokenContextHolder;
import com.neusoft.hifly.core.token.config.JwtConfig;
import com.neusoft.hifly.security.EncodeUtils;

@SuppressWarnings("rawtypes")
@ControllerAdvice
public class ResponseDataHandler implements ResponseBodyAdvice {

	@Autowired(required = false)
	private JwtConfig jwtConfig;
	@Autowired(required = false)
	private RedisCache redisCache;

	@Override
	public boolean supports(final MethodParameter returnType, final Class converterType) {
		return true;
	}

	/**
	 * 拦截@RestController返回值，返回值中添加刷新Token属性
	 */
	@Override
	public Object beforeBodyWrite(final Object body, final MethodParameter returnType,
			final MediaType selectedContentType, final Class selectedConverterType, final ServerHttpRequest request,
			final ServerHttpResponse response) {
		if (body instanceof ApiResponse) {
			final ApiResponse<?> map = (ApiResponse<?>) body;
			if (StringUtils.isEmpty(map.getRefreshToken())) {

				// 从请求头中获取token
				final String token = TokenContextHolder.get().getToken();
				// 去redis里面获取公钥
				final String secret = redisCache.get(EncodeUtils.md5Encode(token));

				map.setRefreshToken(
						JwtUtil.createPayLoad(secret, jwtConfig.getExpire(), TokenContextHolder.get(), redisCache));
			}
		}
		return body;
	}
}
